package be.dioubs.sportTrack.adapter;

import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import be.dioubs.sportTrack.common.Converter;
import be.dioubs.sportTrack.dto.TrackDTO;

public class DbAdapter {

	private static final String DATABASE_NAME = "SportTrackDb";
	private static final String DATABASE_TABLE = "sportTrack";
	private static final int DATABASE_VERSION = 5;

    private static final String DATABASE_CREATE =
        "create table " + DATABASE_TABLE + " (_id integer primary key autoincrement, "
    	+ "title text not null , " 
        + "description text not null, sport text not null, " 
        + "date integer not null, distance_nb real not null, distance_unit not null, "
        + "time text not null, heart_rate_moy text, "
        + "heart_rate_max text not null, fitness_level integer not null); ";
    
    private static final String TAG = "DIOUBS";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
            onCreate(db);
        }
    }

    public DbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    public DbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    // FETCH
    public Cursor fetchTrack(long rowId) throws SQLException {
        Cursor mCursor = mDb.query(true, DATABASE_TABLE,
        		new String[] {
		        		TrackDTO.KEY_ID, TrackDTO.KEY_TITLE,
		        		TrackDTO.KEY_DESCRIPTION, TrackDTO.KEY_DISTANCE_NB, TrackDTO.KEY_DISTANCE_UNIT,
		        		TrackDTO.KEY_FITNESS_LEVEL, TrackDTO.KEY_HEART_RATE_MAX,
		        		TrackDTO.KEY_HEART_RATE_MOY,  TrackDTO.KEY_SPORT,
		        		TrackDTO.KEY_TIME, TrackDTO.KEY_DATE
                }, TrackDTO.KEY_ID + "=" + rowId, null,
                null, null, null, null);

        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        
        return mCursor;
    }
    
    public Cursor fetchAllTracks() {
        return mDb.query(DATABASE_TABLE,
        		new String[] {
		        		TrackDTO.KEY_ID, TrackDTO.KEY_TITLE,
		        		TrackDTO.KEY_DESCRIPTION, TrackDTO.KEY_DISTANCE_NB, TrackDTO.KEY_DISTANCE_UNIT,
		        		TrackDTO.KEY_FITNESS_LEVEL, TrackDTO.KEY_HEART_RATE_MAX,
		        		TrackDTO.KEY_HEART_RATE_MOY,  TrackDTO.KEY_SPORT,
		        		TrackDTO.KEY_TIME, TrackDTO.KEY_DATE
        		}, null, null, null, null , TrackDTO.KEY_DATE + " DESC", "");
    }    

    // INSERT
    public long createTrack(TrackDTO trackDTO) {
        ContentValues args = Converter.trackDtoToContentValues(trackDTO);

        long rc =  mDb.insert(DATABASE_TABLE, null, args);
        
        return rc;
    }    

    public void createTestTracks() {
    	for(int i=0; i < 50; i++) {
    		TrackDTO trackDTO = new TrackDTO();
    		trackDTO.setTitle("Title " + i);
    		trackDTO.setDescription("Description " + i);
    		trackDTO.setTime("time");
    		trackDTO.setDistanceNb(150l);
    		trackDTO.setDistanceUnit("m");
    		trackDTO.setSport("run");
    		trackDTO.setDate(new Date());
    		trackDTO.setHeartRateMoy("hrMoy");
    		trackDTO.setHeartRateMax("hrMax");
    		trackDTO.setFitnessLevel("fitnessLevel");
    		
    		createTrack(trackDTO);
    	}
    }    
    
    // UPDATE
    public boolean updateTrack(TrackDTO trackDTO) {
        ContentValues args = Converter.trackDtoToContentValues(trackDTO);

        Long rowId = trackDTO.getId();
        
        return mDb.update(DATABASE_TABLE, args, TrackDTO.KEY_ID + "=" + rowId, null) > 0;
    }
    
    // DELETE    
    public boolean deleteTrack(long rowId) {

        return mDb.delete(DATABASE_TABLE, TrackDTO.KEY_ID + "=" + rowId, null) > 0;
    }
    
    public boolean deleteAllTrack() {

        return mDb.delete(DATABASE_TABLE, null, null) > 0;
    }    
}
